package com.whcoding.base.project.common;

import com.whcoding.base.project.pojo.PageParamVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.Collections;
import java.util.List;

/**
 * @author Manager
 */
public class BasicsPageUtil {

    /**
     * Jpa需要的分页对象
     * @param page
     * @return
     */
    public static PageRequest buildPageable(PageParamVO page) {
        Sort sort = Sort.unsorted();
        if (!StringUtils.isEmpty(page.getSortIndx())) {
            if(StringUtils.isEmpty(page.getSortDir())) {
                page.setSortDir(Sort.Direction.ASC.name());
            }
//            sort = new Sort(Sort.Direction.fromString(page.getSortDir()), page.getSortIndx());
        }
        if (page.getCurPage() == null ) {
            page.setCurPage(1);
        }
        if (page.getPageSize() == null ) {
            page.setPageSize(10000);
        }
        PageRequest pageRequest = PageRequest.of(page.getCurPage() - 1, page.getPageSize(), sort);
        return pageRequest;
    }

    /**
     * 填充数据
     * @param pageParam
     * @param page
     * @return
     */
    public static PageParamVO fillPageParamResult(PageParamVO pageParam, Page page) {
        pageParam.setData(page.getContent());
        pageParam.setTotalRecords(page.getTotalElements());
        return pageParam;
    }

    /**
     * 手动分页
     * @param srcList
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public static <T> List<T> resultListForPage(List<T> srcList, int pageNumber, int pageSize ){
        if(CollectionUtils.isEmpty(srcList) || pageNumber <= 0 || pageSize <= 0){
            return Collections.emptyList();
        }
        //分页后的集合
        List<T> list;

        int beginData = (pageNumber - 1) * pageSize + 1;
        int endData = pageNumber * pageSize;
        int count = srcList.size();

        if(beginData > count){
            return Collections.emptyList();
        }

        //第一页
        if(pageNumber == 1){
            if(count <= pageSize){
                list = srcList;
            }else {
                list = srcList.subList(beginData-1,endData-1);
            }
        }else {
            //大于第一页时
            if(count <= pageSize * pageNumber){
                list = srcList.subList(beginData-1,count-1);
            }else {
                list = srcList.subList(beginData-1,endData-1);
            }
        }
        return list;
    }
}
